package com.example.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.example.config;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2024-01-25 14:23]
 * @copyright: 2024 echovin.com
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> {
            SaRouter.match("/**")
                    .notMatch("/saLogin","/doLogin","/sa-login.html","/sa-res/**")
                    .check(s->{
                        // 未登录时直接转发到login.html页面
                        if (!StpUtil.isLogin()) {
                            SaHolder.getRequest().forward("/saLogin");
                            SaRouter.back();
                        }
                    });
            //角色校验
            SaRouter.match("/user/*", s->StpUtil.checkRoleOr("admin", "user"));
            SaRouter.match("/orders/*", s->StpUtil.checkRoleOr("admin", "orders"));
            //权限校验
            SaRouter.match("/user/list", s->StpUtil.checkPermission("/user/list"));
            SaRouter.match("/user/add", s->StpUtil.checkPermission("/user/add"));
            SaRouter.match("/orders/list", s->StpUtil.checkPermission("/orders/list"));
            SaRouter.match("/orders/add", s->StpUtil.checkPermission("/orders/add"));
        }));
    }
}